package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IuserService;
import com.cskaoyan.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenxu
 * @since 2022/04/22 21:18
 */
@Slf4j
@Service
public class UserServiceImpl implements IuserService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper converterMapper;
    @Autowired
    UserVerifyMapper verifyMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest loginRequest, HttpServletResponse servletResponse) {
        UserLoginResponse response = new UserLoginResponse();
        UserLoginResponse userLoginResponse = null;
        try {
            //判空验证
            loginRequest.requestCheck();
            //密码加密处理
            String userpassword = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
            Example example = new Example(Member.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("username",loginRequest.getUserName()).andEqualTo("password",userpassword);
            Member member = memberMapper.selectOneByExample(example);

            //判断member是否为空或者密码是否正确
            log.info("查找用户信息成功;用户信息member:{}",JSON.toJSON(member));
            if (member == null || (!member.getPassword().equals(userpassword))){
                response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
                response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
                return response;
            }
            //判断是否已经激活
            if ("N".equals(member.getIsVerified())){
                response.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
                response.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
                return response;
            }
            //将用户id和用户名放进cookie
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("id",member.getId().toString());
            hashMap.put("username",member.getUsername());
            String token = JwtTokenUtils.builder().msg(JSON.toJSONString(hashMap)).build().creatJwtToken();
            //Cookie access_token = new Cookie("access_token", token);
            //这里注意：cookie需要存在应用根目录下，还需设置一定的时间
            Cookie access_token = CookieUtil.genCookie("access_token", token, "/", 60 * 60 * 24);
            servletResponse.addCookie(access_token);
            log.info("tonken放入成功：token{}",token);
            //todo 是否需要验证
            userLoginResponse = converterMapper.converter(member);
            userLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
            userLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            userLoginResponse.setToken(token);
        } catch (Exception e) {
            log.info("验证失败，原因：{}{}",e.getCause(),e.getStackTrace());
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return userLoginResponse;
    }

    @Override
    public UserVerifyResponse verify(UserVerifyRequest userVerifyRequest) {
        UserVerifyResponse response = new UserVerifyResponse();
        try {
            userVerifyRequest.requestCheck();
            //修改用户表的验证记录
            Member member = new Member();
            member.setIsVerified("Y");
            member.setUpdated(new Date());
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username",userVerifyRequest.getUserName());

            int effectRows = memberMapper.updateByExampleSelective(member, example);
            if (effectRows != 1){
                //必要大的参数不正确
                response.setCode(UserRetCode.REQUEST_DATA_ERROR.getCode());
                response.setMsg(UserRetCode.REQUEST_DATA_ERROR.getMessage());
            }
            //修改验证表的信息记录
            Example example1 = new Example(UserVerify.class);
            example1.createCriteria().andEqualTo("username",userVerifyRequest.getUserName())
                    .andEqualTo("uuid",userVerifyRequest.getUuid());
            UserVerify userVerify = new UserVerify();
            userVerify.setIsVerify("Y");
            int Rows = verifyMapper.updateByExampleSelective(userVerify, example1);
            if (Rows != 1){
                //必要的参数不正确
                response.setCode(UserRetCode.REQUEST_DATA_ERROR.getCode());
                response.setMsg(UserRetCode.REQUEST_DATA_ERROR.getMessage());
            }
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.info("验证失败，原因：{}{}",e.getCause(),e.getStackTrace());
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
}
